<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>MCU Conference</title>
    <script type="text/javascript" src="SkyRTC-client.js"></script>
    <script type="text/javascript" src="jquery-1.10.2.js"></script>
    <script type="text/javascript" src="jquery-ui-1.10.1.min.js"></script>
    <script type="text/javascript" src="camerainfos.js"></script>
    <script type="text/javascript" src="common.js"></script>
    <script type="text/javascript" src="splitscreen.js"></script>
    <link href="css/main.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript">
        var rtc;
        var mcu = VideoMCU();   //分屏MCU
        var logManager;

        var currRoomNum;//获取参数roomNum
        var userID; //用户id
        var userName; //用户姓名
        var defaultShowVideo; //默认是否显示视频
        var currVideoId; //当前正在使用的摄像头id

        var isAudioOn = false; //是否开启麦克风, 默认关闭
        var videoUsers = []; //用于分屏的用户信息

        function init() {
            currRoomNum = request("roomNum");
            userID = request("userId");
            userName = request("userName");
            defaultShowVideo = request("defaultShowVideo") || "show";

            //初始化日志管理器
            logManager = new LogManager(userID, "log/uploadlog");

            //初始化RTC相关的回调函数
            initRTC();
            //初始化MCU分屏功能
            mcu.init({
                "defaultImgPath": "defaultConf.bmp",    //无视频时的默认图片路径
                "videoContainerId": "screenContainer",  //视频容器div
                "localVideoUserId": userID
            });

            var videoName = request("videoName");
            //去除字符串中的双引号
            videoName = videoName.replace(/"/g, "");

            //获取摄像头列表，并在获取后进行初始化
            initAndGetCameraInfos(function (videoInfos) {
                console.log("获取摄像头列表成功", videoInfos);
                //如果url中未指定摄像头，则自己指定
                if (videoName == null || videoName.length == 0) {
                    //获取摄像头列表的第一个摄像头，作为默认摄像头
                    currVideoId = getFreeCamId();
                } else {  //如果已指定，则需要根据名称获取摄像头id
                    currVideoId = getCameraIdByName(videoName);
                }

                if (currVideoId == null || currVideoId.length == 0) {
                    console.log("MCU初始化失败，因未获取到有效的摄像头");
                    return;
                }

                if (currRoomNum != null && currRoomNum.length > 0) {
                    join(currRoomNum);
                }

                initDebug(); //初始化调试按钮信息
            });
        }

        function initRTC() {
            rtc = SkyRTC();

            //成功创建WebSocket连接
            rtc.on("socket_connected", function (socket) {
                console.log("socket创建成功", socket);
                var audio = request("audio");
                var speaker = request("speaker");
                isAudioOn = getParams(audio);
                speaker = getParams(speaker);
                console.info("音频状态是:" + isAudioOn + ", speaker:" + speaker);
                console.info("创建WebSocket的时候audio=" + isAudioOn);
                //创建本地视频流
                if (currVideoId == "" || currVideoId == undefined) {
                    console.log("摄像头未指定，使用默认摄像头来进行rtc.createStream");
                    currVideoId = null;
                }

                rtc.createStreamAndInit(getMediaOptions(currVideoId, isAudioOn));
            });

            //断开WebSocket连接
            rtc.on("socket_closed", function(socket){
                console.log("WebSocket连接已断开，开始重置RTC与MCU", socket);
                //断开后重新初始化rtc，防止后面再次调用
                initRTC();
                //清理页面
                mcu.cleanUp();
                console.log("RTC与MCU重置完毕");
            });

            //创建本地视频流成功
            rtc.on("stream_created", function (stream) {
                var myVideoUrl = URL.createObjectURL(stream);
                var user1 = {"userId": userID, "userName": userName, "videoPosition": 1, "videoURL": myVideoUrl};

                //页面第一次加载，创建本地视频成功后，直接进行1分屏
                if(mcu.currVideoUsers.length == 0) {
                    mcu.SplitVideoScreen(1, [user1]);
                }else{  // 切换摄像头成功后，将本地用户新的视频地址更新到MCU中
                    mcu.updateUserVideo(user1);
                }
            });

            //创建本地视频流失败
            rtc.on("stream_create_error", function () {
                console.warn("创建本地视频流失败");
            });

            //接收到其他用户的视频流
            rtc.on('pc_add_stream', function (stream, socketId) {
                var peerInfo = rtc.getUserInfoBySocketId(socketId);
                console.log("pc_add_stream,收到用户视频流,userId:" + peerInfo.userName);
                if (peerInfo == null || IsStringEmpty(peerInfo.userId)) {
                    console.warn("pc_add_stream, 增加新用户失败，因参数不全", peerInfo);
                    return;
                }

                var myVideoUrl = URL.createObjectURL(stream);
                var user = {"userId": peerInfo.userId, "userName": peerInfo.userName, "videoURL": myVideoUrl};

                //如果用户已经在MCU中存在，则直接更新即可（在客户端切换摄像头的时候，其他用户会触发下面的代码）
                if(mcu.isUserExists(peerInfo.userId)){
                    console.log("用户已存在于MCU中，直接更新该用户");
                    mcu.updateUserVideo(user);
                    return;
                }

                console.log("开始将用户" + peerInfo.userName + "存储到videoUsers中");
                videoUsers.push(user);
                if (rtc.isPeerConnectionsReady()) {
                    console.log("所有用户的视频都已准备好，可以开始分屏");
                    if (videoUsers.length >= 1) {
                        console.log("将用户加入到MCU中，用户为", videoUsers);
                        mcu.addUserVideo(videoUsers);
                        videoUsers = [];
                    }

                    console.log("开始调用bound.JSVideoNum...");
                    try {
                        bound.jSVideoNum("'2'", '');
                    } catch (error) {
                        console.log("在调用bound.jsVideoNum时出错 + " + error);
                    }
                }
            });

            //删除其他用户
            rtc.on('remove_peer', function (userId) {
                console.log("有用户退出，用户id：" + userId);
                if (!IsStringEmpty(userId)) {
                    console.log("开始从视频列表中删除用户"+ userId);
                    mcu.removeUserVideo(userId);
                } else {
                    console.warn("remove_peer, 删除用户失败，因参数不全", userId);
                }
            });
        }

        //获取媒体相关属性，用于加载摄像头和麦克风
        function getMediaOptions(videoId, isAudioOn){
            return {
                video: {
                    mandatory: {"maxWidth": "1920", "maxHeight": "1080"},
                    "optional": [{"sourceId": videoId}, {"frameRate": 60}, {"aspectRatio": 16 / 9}]
                },
                audio: isAudioOn
            };
        }

        //连接WebSocket视频控制中心
        function connectWSServer() {
            console.log("开始连接WebSocket");
            if (!IsStringEmpty(currRoomNum)) {
                //连接WebSocket服务器
                var wsUrl = "wss:" + window.location.href.substring(window.location.protocol.length).split('#')[0];
                rtc.connect(wsUrl, currRoomNum, userID, userName);
                console.log("连接 WebSocket服务器:" + wsUrl, currRoomNum);
            } else {
                console.log("因参数中会议号为空，暂时不初始化websocket连接");
            }
        }

        //切换摄像头，参数为摄像头名称
        function switchCamera(camName) {
            console.log("开始切换摄像头，camName:" + camName);
            var camId = getCameraIdByName(camName);
            rtc.switchStream(getMediaOptions(camId, isAudioOn));
        }

        //获取视频数量
        function getVideosNumber() {
            return document.getElementsByTagName("video").length;
        }

        //加入会议室
        function join(roomid) {
            console.log("开始加入会议室,roomId:" + roomid);
            if (roomid == null || roomid.length == 0) {
                console.log("roomid为空，加入会议失败");
                return;
            }

            if (rtc.isLive()) {
                console.log("会议已经开始，不需要再次join");
                return;
            }

            //如果没有摄像头，需要再次指定（在不刷新页面的情况下，多次join会出现摄像头错乱，所以重新指定比较好）
            if (currVideoId == null) {
                currVideoId = getFreeCamId();
            }

            currRoomNum = roomid;
            setTimeout("connectWSServer()", parseInt(1200 * Math.random()));
        }

        //退出会议室，并断开WebSocket连接
        function unjoin() {
            console.log("开始断开会议室, roomId:" + currRoomNum);
            currVideoId = null;
            currRoomNum = null;
            if (rtc.isLive()) {
                rtc.unConnect();
            } else {
                console.log("rtc连接已处于关闭状态，不需要再次关闭");
            }
        }

        //按数字分屏
        function divScreen(num) {
            console.log("开始分屏，num:" + num);
            num = parseInt(num);
            mcu.SplitVideoScreen(num);
        }

    </script>
</head>
<body onload="init();">
<div id="debugdiv">
    <script type="text/javascript">
        function initDebug(){
            //初始化日志上传按钮点击事件
            $("#uploadLog").on('click', function () {
                if (logManager.isOriginnalConsole) {
                    logManager.takeOverConsole();
                    $(this).val("取消上传日志");
                } else {
                    logManager.recoverConsole();
                    $(this).val("上传日志");
                }
            });

            //初始化切换摄像头下拉列表
            var camIdNameMap = getCameraInfos();
            for(var cid in camIdNameMap){
                $("#switchcameraddl").append("<option value='"+cid+"'>"+camIdNameMap[cid]+"</option>");
            }

            $("#switchcameraddl").change(function(){
               switchCamera($(this).find("option:selected").text());
            });

            $("#blockdebug").on("click",function(){
                $("#debugdiv").slideToggle();
            });
        }
    </script>
    分屏:
    <select name="分屏" onchange="divScreen(this.options[this.options.selectedIndex].value)" title="分屏">
        <option value="1">1分屏</option>
        <option value="2">2分屏</option>
        <option value="3">3分屏</option>
        <option value="4">4分屏</option>
        <option value="5">5分屏</option>
        <option value="6">6分屏</option>
        <option value="7">7分屏</option>
        <option value="8">8分屏</option>
        <option value="9">9分屏</option>
        <option value="10">10分屏</option>
        <option value="13">13分屏</option>
        <option value="16">16分屏</option>
    </select>
    &nbsp;
    切换摄像头
    <select id="switchcameraddl" name="切换摄像头" title="切换摄像头"></select>
    &nbsp;
    <input type="button" id="uploadLog" value="上传日志"/>
</div>
<div id="screenContainer"></div>
<input type="button" id="blockdebug" />
</body>
</html>
